/**
 *
 * @author Anastasiya
 *
 */

#include "testlib.h"
#include "util.h"
#include <direct.h>
#include <windows.h>
#include <tchar.h>
#include <iostream>


using namespace std;



TestFramework::TestFramework(Algorithm* algorithm1, Algorithm* algorithm2){
	this->algorithm1 = algorithm1;
	this->algorithm2 = algorithm2;
}

TestFramework::~TestFramework(){
}

void TestFramework::test(string resultPath, string testPath){
	string algorithmName1 = "";
	string algorithmName2 = "";
	
	if(algorithm1 != NULL){
		algorithmName1 = algorithm1->getName();
	}
	if(algorithm2 != NULL){
		algorithmName2 = algorithm2->getName();
	}

	TexWriter *writer = new TexWriter(algorithmName1, algorithmName2);
	
	_chdir(testPath.c_str());
	walkFileTree(resultPath, writer);
	writer->write(TEX_FILENAME);
}


void TestFramework::walkFileTree(string resultPath, TexWriter* writer){
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;

	TCHAR curDir[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, curDir);

	hFind = FindFirstFile(FILE_MASK_ANY.c_str(), &FindFileData);
	BOOL haveMoreFiles = (hFind != INVALID_HANDLE_VALUE);
	while(haveMoreFiles){
		if(strcmp(FindFileData.cFileName, DIR_NAME_UPPER.c_str()) == 0 || strcmp(FindFileData.cFileName, DIR_NAME_CURRENT.c_str()) == 0){
		}else if(FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) {
			_chdir(FindFileData.cFileName);
			string newResultPath = concatPath(resultPath, string(FindFileData.cFileName));
			walkFileTree(newResultPath, writer);
			_chdir(DIR_NAME_UPPER.c_str());
		}else{
			string fileAbsolutePath = concatPath(string(curDir), string(FindFileData.cFileName));
			runTest(resultPath, fileAbsolutePath, writer);
		}
		haveMoreFiles = FindNextFile(hFind, &FindFileData);
	}
	FindClose(hFind);
}



void TestFramework::runTest(string resultPath, string fileAbsolutePath, TexWriter* writer){
	if(fileAbsolutePath.compare(TEX_FILENAME) == 0){
		return;
	}
	TestResult* result1 = NULL;
	if(algorithm1 != NULL){
		result1 = algorithm1->execute(resultPath, fileAbsolutePath);
	}

	TestResult* result2 = NULL;
	if(algorithm2 != NULL){
		result2 = algorithm2->execute(resultPath, fileAbsolutePath);
	}


	fileAbsolutePath = latexString(fileAbsolutePath);
	writer->addResult(fileAbsolutePath, result1, result2);

	if(result1 != NULL){
		delete result1;
	}
	if(result2 != NULL){
		delete result2;
	}
}

